<template>
  <div>
    <el-form
      :model="formData"
      ref="form"
      label-width="120px"
      label-position="right"
    >
      <el-form-item :label="$t('sys.is_enable')" prop="enabled">
        <el-switch v-model="formData.enabled"></el-switch>
      </el-form-item>
      <el-form-item
        :label="$t('sys.corpId')"
        prop="corpId"
        :rules="[
          formData.enabled
            ? {
                required: true,
                message: $t('sys.corpId_not_null'),
                trigger: 'change',
              }
            : {},
          {
            pattern: /^[a-zA-Z0-9]{1,128}$/,
            message: $t('sys.enter_valid_corpId'),
            trigger: 'change',
          },
        ]"
      >
        <el-input
          style="width: 500px"
          v-model="formData.corpId"
          :placeholder="$t('sys.enter_corpId')"
          :maxlength="128"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.agentId')"
        prop="agentId"
        :rules="[
          formData.enabled
            ? {
                required: true,
                message: $t('sys.agentId_not_null'),
                trigger: 'change',
              }
            : {},
          {
            pattern: /^[a-zA-Z0-9]{1,128}$/,
            message: $t('sys.enter_valid_agentId'),
            trigger: 'change',
          },
        ]"
      >
        <el-input
          style="width: 500px"
          v-model="formData.agentId"
          :placeholder="$t('sys.enter_agentId')"
          :maxlength="128"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.appKey')"
        prop="appKey"
        :rules="[
          formData.enabled
            ? {
                required: true,
                message: $t('sys.appKey_not_null'),
                trigger: 'change',
              }
            : {},
        ]"
      >
        <el-input
          style="width: 500px"
          v-model="formData.appKey"
          :placeholder="$t('sys.enter_appKey')"
          :maxlength="128"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.appSecret')"
        prop="appSecret"
        :rules="[
          formData.enabled
            ? {
                required: true,
                message: $t('sys.appSecret_not_null'),
                trigger: 'change',
              }
            : {},
        ]"
      >
        <el-input
          style="width: 500px"
          v-model="formData.appSecret"
          :placeholder="$t('sys.enter_appSecret')"
          :maxlength="128"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.appUrl')"
        prop="url"
        :rules="[
          formData.enabled
            ? {
                required: true,
                message: $t('sys.appUrl_not_null'),
                trigger: 'change',
              }
            : {},
        ]"
      >
        <div class="appUrl">
          {{ formData.url }}
          <i
            v-if="formData.url"
            class="el-input__icon el-icon-document-copy f18 poi copyIcon"
            @click="copy(formData.url)"
          ></i>
          <i
            v-if="formData.url"
            class="el-input__icon el-icon-refresh f18 poi copyIcon"
            @click="refresh('url')"
          ></i>
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('sys.mobileUrl')"
        prop="appUrl"
        :rules="[
          formData.enabled
            ? {
                required: true,
                message: $t('sys.mobileUrl_not_null'),
                trigger: 'change',
              }
            : {},
        ]"
      >
        <div class="appUrl">
          {{ formData.appUrl }}
          <i
            v-if="formData.appUrl"
            class="el-input__icon el-icon-document-copy f18 poi copyIcon"
            @click="copy(formData.appUrl)"
          ></i>
          <i
            v-if="formData.url"
            class="el-input__icon el-icon-refresh f18 poi copyIcon"
            @click="refresh('appUrl')"
          ></i>
        </div>
      </el-form-item>

      <el-form-item
        :label="$t('sys.correlation')"
        prop="correlation"
        :rules="[
          formData.enabled
            ? {
                required: true,
                validator: checkCorrelation,
                trigger: 'change',
              }
            : {},
        ]"
      >
        <div>
          <el-select
            v-model="formData.correlation"
            :placeholder="$t('sys.choose_correlation')"
          >
            <el-option
              v-for="item in CORRELATION_ENUM"
              :key="item.value"
              :value="item.value"
              :label="$t(item.label)"
            ></el-option>
          </el-select>
          <div>
            <el-input
              v-if="formData.correlation === '-1'"
              class="mt10"
              style="width: 500px"
              v-model="correlationStr"
              :placeholder="$t('sys.enter_field')"
            />
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="submit">{{
          $t("sys.submit")
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { copy } from "@/utils/util";
import {
  getHmpluginpropertyList,
  postHmpluginproperty,
} from "@/apis/paas/HmPluginPropertyController.js";
const CORRELATION_ENUM = [
  {
    label: "sys.account",
    value: "username",
  },
  {
    label: "sys.job_number",
    value: "job_number",
  },
  {
    label: "sys.cellphone_number",
    value: "mobile",
  },
  {
    label: "sys.email",
    value: "email",
  },
  {
    label: "sys.other",
    value: "-1",
  },
];
export default {
  data() {
    var checkCorrelation = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t("sys.correlation_not_null")));
      } else if (value === "-1") {
        if (!this.correlationStr) {
          callback(new Error(this.$t("sys.correlation_not_null")));
        } else if (!/[a-zA-Z0-9_]{1,64}/.test(this.correlationStr)) {
          callback(new Error(this.$t("sys.enter_valid_field")));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    return {
      initLoading: false,
      checkCorrelation,
      CORRELATION_ENUM,
      copy,
      correlationStr: "",
      formData: {
        enabled: false,
        corpId: "",
        agentId: "",
        appKey: "",
        appSecret: "",
        url: "",
        appUrl: "",
        correlation: "username",
      },
      loading: false,
    };
  },
  components: {},
  created() {
    this.getDetail();
  },
  methods: {
    getDetail() {
      this.initLoading = true;
      getHmpluginpropertyList({ group: this.$route.query.group })
        .then((res) => {
          let correlation = res["dingtalk.correlation"] || "username";
          if (
            !["username", "job_number", "mobile", "email"].includes(correlation)
          ) {
            correlation = "-1";
            this.correlationStr = res["dingtalk.correlation"];
          }
          this.formData = {
            enabled: res["dingtalk.enabled"] === "true",
            corpId: res["dingtalk.corpId"],
            agentId: res["dingtalk.agentId"],
            appKey: res["dingtalk.appKey"],
            appSecret: res["dingtalk.appSecret"],
            url:
              res["dingtalk.url"] ||
              `${window.location.origin}/redirect.html?corpId=$CORPID$`,
            appUrl:
              res["dingtalk.appUrl"] ||
              `${window.location.origin}/dingtalk/redirect.html?corpId=$CORPID$`,
            correlation,
          };
        })
        .finally(() => {
          this.initLoading = false;
        });
    },
    async submit() {
      try {
        await this.$refs.form.validate();
        this.loading = true;
        const {
          enabled,
          corpId,
          agentId,
          appKey,
          appSecret,
          url,
          appUrl,
          correlation,
        } = this.formData;
        const data = {
          "dingtalk.enabled": enabled,
          "dingtalk.corpId": corpId,
          "dingtalk.agentId": agentId,
          "dingtalk.appKey": appKey,
          "dingtalk.appSecret": appSecret,
          "dingtalk.url": url,
          "dingtalk.appUrl": appUrl,
          "dingtalk.correlation":
            correlation === "-1" ? this.correlationStr : correlation,
        };
        for (const key in data) {
          data[key] =
            typeof data[key] === "string" ? data[key].trim() : data[key];
        }
        postHmpluginproperty(data)
          .then((res) => {
            this.$message.success(this.$t("sys.operation_success"));
          })
          .finally(() => {
            this.loading = false;
          });
      } catch (error) {
        console.log(error);
      }
    },
    refresh(field) {
      if (field === "url") {
        this.formData.url = `${window.location.origin}/redirect.html?corpId=$CORPID$`;
      } else {
        this.formData.appUrl = `${window.location.origin}/dingtalk/redirect.html?corpId=$CORPID$`;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.appUrl {
  min-height: 32px;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  word-break: break-all;
  padding: 0 15px;
  width: 500px;
  box-sizing: border-box;
  .copyIcon {
    color: #3d64ff;
  }
}
</style>
